package lock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author lyx
 * @Date 2021/6/25 12:49
 * 读写锁
 * 读-读可以共存
 * 读-写不能共存
 * 写-写不能共存
 * 写的方法,得用写锁,不然会被插队
 */
public class ReadWriteLockTest {
    public static void main(String[] args) {
        //new一个cache对象,去.方法
        MyCacheLock myCacheLock = new MyCacheLock();
        //写入
        for (int i = 1; i <= 10; i++) {
            final int temp = i;
            new Thread(()->{
                //for10个线程,执行写入方法put,传参数 (i,i)
                myCacheLock.put(temp+"",temp+"");
            },String.valueOf(i)).start();//String.valueOf(i)当前线程名字
        }
        //读取
        for (int i = 1; i <= 10; i++) {
            final int temp = i;
            new Thread(()->{
                myCacheLock.get(temp+"");
            },String.valueOf(i)).start();
        }
    }
}

//加读写锁的自定义缓存
class MyCacheLock{
    //volatile原子性
    private volatile Map<String ,Object> map = new HashMap<>();
    //读写锁
    private ReadWriteLock readWriteLock =  new ReentrantReadWriteLock();
    //写入
    public void put(String key,Object value){
        try {
            //加读写锁
            readWriteLock.writeLock().lock();
            System.out.println(Thread.currentThread().getName()+"  正在写入");
            map.put(key, value);
            System.out.println(Thread.currentThread().getName()+"  写入成功!!!");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //解锁
            readWriteLock.writeLock().unlock();
        }
    }
    //读取
    public void get(String key){
        try {
            System.out.println(Thread.currentThread().getName()+"正在读取");
            map.get(key);
            System.out.println(Thread.currentThread().getName()+"读取成功!!!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}